import { useMessage } from '@/hooks'
import { api, useAxiosResponse } from '@/api'
import { useComDesignStoreWithOut } from '../../index'
import { getRenderInfo, loadingRelyCurtomCom } from '../render/index'

import type {
  SysCustomComInfoOutupu,
  SysCustomComDesignOutupu,
  SysCustomComPageInfoOutupu,
} from './model'
import { type BwCustomComDesignInfoModel } from '@bitwit/base-com-render'

const { notification, createWarningModal } = useMessage()

/** 获取组件信息 */
export function getCortomComList(keyWord?: string, groups?: Array<string>) {
  return new Promise<Array<SysCustomComInfoOutupu>>((resolve, reject) => {
    api
      .apiSysAppPageGetListPost({
        pageNum: null,
        pageSize: null,
        keyWord: keyWord,
        groups: groups,
      })
      .then((res) => {
        const resData = useAxiosResponse<SysCustomComPageInfoOutupu>(res)
        const rows: Array<SysCustomComInfoOutupu> = resData?.rows ?? []

        resolve(rows)
      })
      .catch((error) => {
        notification.error({ message: '获取自定义组件分组列表失败，请检查！' })
        reject(error)
      })
  })
}

/** 获取组件信息 */
export function getComDesignInfo(appId?: string, pageId?: string) {
  return new Promise<BwCustomComDesignInfoModel | null>((resolve, reject) => {
    api
      .apiSysAppPageGetDesignPost({
        appId,
        pageId,
      })
      .then((res) => {
        const designStore = useComDesignStoreWithOut()
        const resData = useAxiosResponse<SysCustomComDesignOutupu>(res)
        const designInfo = resData?.designInfo
          ? JSON.parse(resData?.designInfo)
          : null
        designStore.setDesignInfo(designInfo)
        resolve(designInfo)
      })
      .catch((error) => {
        notification.error({ message: '获取自定义组件设计信息失败，请检查！' })
        reject(error)
      })
  })
}

/** 保存组件设计信息 */
export function saveComDesignInfo(
  appId: string,
  pageId: string,
  designInfo: Nullable<BwCustomComDesignInfoModel>
) {
  return new Promise<boolean>((resolve, reject) => {
    if (designInfo) {
      api
        .apiSysAppPageSetDesignPost({
          appId,
          pageId,
          designInfo: JSON.stringify(designInfo),
        })
        .then((res) => {
          const resData = useAxiosResponse<boolean>(res)
          !!resData
            ? notification.success({
                message: '保存自定义组件设计信息成功！',
              })
            : notification.error({
                message: '保存自定义组件设计信息失败，请检查！',
              })

          resolve(!!resData)
        })
        .catch((error) => {
          notification.error({
            message: '保存自定义组件设计信息失败，请检查！',
          })
          reject(error)
        })
    } else {
      createWarningModal({ content: '当前组件还未开始设计，请先进行设计！' })
      reject()
    }
  })
}

/** 获取自定义组件渲染信息 */
export function getCustomComDesignInfo(appId: string, pageId: string) {
  return new Promise<BwCustomComDesignInfoModel | null>((resolve, reject) => {
    const designStore = useComDesignStoreWithOut()
    const curInfos = designStore.curCustomComRenderInfo
    const curComInfo = curInfos[pageId]

    if (curComInfo) {
      resolve(curComInfo)
    } else {
      api
        .apiSysAppPageGetDesignPost({
          appId,
          pageId,
        })
        .then((res) => {
          const resData = useAxiosResponse<SysCustomComDesignOutupu>(res)
          const designInfo = resData?.designInfo
            ? JSON.parse(resData?.designInfo)
            : null

          designStore.setCustomComRenderInfo(pageId ?? '', designInfo)
          resolve(designInfo)
        })
        .catch((error) => {
          notification.error({
            message: '获取自定义组件设计信息失败，请检查！',
          })
          reject(error)
        })
    }
  })
}

/** 锁定设计器 （保存组件渲染信息） */
export function saveCustomComRenderInfo(
  appId: string,
  pageId: string,
  designInfo: Nullable<BwCustomComDesignInfoModel>
) {
  return new Promise<boolean>((resolve, reject) => {
    if (designInfo) {
      loadingRelyCurtomCom(designInfo).then(() => {
        const renderInfo = getRenderInfo(designInfo)

        api
          .apiSysAppPageSetRenderPost({
            appId,
            pageId,
            renderInfo: JSON.stringify(renderInfo),
          })
          .then((res) => {
            const resData = useAxiosResponse<boolean>(res)
            !!resData
              ? notification.success({
                  message: '保存自定义组件渲染信息成功！',
                })
              : notification.error({
                  message: '保存自定义组件渲染信息失败，请检查！',
                })

            resolve(!!resData)
          })
          .catch((error) => {
            notification.error({
              message: '保存自定义组件渲染信息失败，请检查！',
            })
            reject(error)
          })
      })
    } else {
      createWarningModal({ content: '当前组件还未开始设计，请先进行设计！' })
      reject()
    }
  })
}
